<?php
/**
 * 获取并解析business报告 (定时，重复执行)
 */

namespace App\Console\Commands\SpApi\Report\Parse;

use App\Logic\Amazon\Api\Report;
use App\Logic\Amazon\Api\RequiredConfig;
use App\Models\Amazon\CreateAndGetReport;
use App\Models\Basics\AmazonAccount;
use Illuminate\Console\Command;
use SellingPartnerApi\ReportType;

class SalesAndTrafficRepeat extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sp-report:get-parse-business-repeat {date=null} {accountId=0}';

    /**
     * The console command description.
     * @var string
     */
    protected $description = 'exe func';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $date = $this->argument('date');
        $accountId = $this->argument('accountId');

        $reportType = ReportType::GET_SALES_AND_TRAFFIC_REPORT;
        $reportDate = date('Y-m-d',strtotime('-2 days')); //执行日期 (每日,自动)
        if (strtotime($date)) {
            if (strtotime($date) < strtotime($reportDate)) {
                $reportDate = $date; //赋值
            }
        }

        $query = CreateAndGetReport::query();
        if ($accountId) {
            $query->where('account_id', $accountId);
        }
        $query->where('report_date', $reportDate);
        $query->where('report_type', $reportType['name']);
        $query->where('is_parse', 0);
        $query->chunk(100, function ($items) use ($reportDate,$reportType){
            if ($items) {
                foreach ($items as $item){
                    $account = AmazonAccount::getModel($item->account_id);
                    if(!$account) continue;
                    $requiredConfig = RequiredConfig::getInit();
                    $apiConfig = $requiredConfig->configuration($account->refresh_token,$account->aws_region);

                    //获取并解析business
                    echo '------start:'.$reportDate.'-'.$account->account.'（'.$account->id.'）------'.PHP_EOL;
                    Report::apiGetAndParseReport($apiConfig,$account,$reportType,$reportDate);
                    sleep(2);
                }
            }
        });
        $this->info('finish!');
    }

}
